/**
 * 地图
 */
class MapItem extends egret.DisplayObjectContainer {
    private map_png = Main.createBitmapByName("map_png");
    /** 初始触摸点 */
    private startPoint: egret.Point = new egret.Point();
    /** 地图极限距离点 */
    private mapMaxPoint: egret.Point = new egret.Point();
    /** 暴露出地图当前位置 */
    public static mapNowPoint: egret.Point = new egret.Point();
    /** 暴露地图宽高 */
    public static mapSize: egret.Point = new egret.Point();

    public constructor() {
        super();
        this.once(egret.Event.ADDED_TO_STAGE, this.init, this);
    }

    private init() {
        this.addChild(this.map_png);
        const oH = this.map_png.width / this.map_png.height;
        MapItem.mapSize.x = this.map_png.width = this.stage.stageWidth * 3;
        MapItem.mapSize.y = this.map_png.height = this.map_png.width / oH;

        MapItem.mapNowPoint.x = this.x = -this.map_png.width * .5 + this.stage.stageWidth * .5;
        MapItem.mapNowPoint.y = this.y = -this.map_png.height * .5 + this.stage.stageHeight * .5;

        this.touchEnabled = true;
        this.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.touchStart, this);
        /** 计算地图极限距离 */
        this.mapMaxPoint.x = -(this.map_png.width - this.stage.stageWidth);
        this.mapMaxPoint.y = -(this.map_png.height - this.stage.stageHeight);

    }
    /** 触摸开始 */
    private touchStart(evt: egret.TouchEvent) {
        this.startPoint.x = evt.stageX;
        this.startPoint.y = evt.stageY;
        this.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.dragMap, this);
        this.addEventListener(egret.TouchEvent.TOUCH_END, this.touchEnd, this);
    }
    /** 拖动地图 */
    private dragMap(evt: egret.TouchEvent) {
        const comput = new egret.Point();
        comput.x = evt.stageX - this.startPoint.x;
        comput.y = evt.stageY - this.startPoint.y;
        this.startPoint.x = evt.stageX;
        this.startPoint.y = evt.stageY;
        /** 
         * 防止顶部超出:
         * 地图容器的y轴小于等于0的时候还在向上拖动
         */
        if (this.y >= 0 - comput.y && comput.y > 0) {
            comput.y = 0;
            this.y = 0;
        }
        /**
         * 防止底部超出:
         * 地图容器的y轴大于等于地图的高度-一个屏的高度, 并且还在向下拖动
         */
        if (this.y <= this.mapMaxPoint.y - comput.y && comput.y < 0) {
            comput.y = 0;
            this.y = this.mapMaxPoint.y
        }
        /** 防止左侧超出 */
        if (this.x >= 0 - comput.x && comput.x > 0) {
            comput.x = 0;
            this.x = 0;
        }
        /** 防止右侧超出 */
        if (this.x <= this.mapMaxPoint.x - comput.x && comput.x < 0) {
            comput.x = 0;
            this.x = this.mapMaxPoint.x;
        }

        MapItem.mapNowPoint.x = this.x += comput.x;
        MapItem.mapNowPoint.y = this.y += comput.y;

        // console.log(`x: ${this.x}`, `y: ${this.y}`);
    }
    /** 触摸结束 */
    private touchEnd() {
        this.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.dragMap, this);
    }

}